package com.kevin.data.batch.component;

import com.kevin.data.batch.configuration.BizItemProcessor;
import com.kevin.data.batch.configuration.BizJobListener;
import com.kevin.data.batch.model.Log;
import jakarta.annotation.Resource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.json.JacksonJsonObjectReader;
import org.springframework.batch.item.json.JsonItemReader;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * JSON 读写处理
 */
@Component
public class JsonBatchComponent {

    @Resource
    private JobRepository jobRepository;

    @Resource
    private BizJobListener jobListener;

    @Resource
    private BizItemProcessor bizItemProcessor;

    @Resource
    private PlatformTransactionManager transactionManager;

    @Bean("jsonJob")
    public Job jsonJob() {
        return new JobBuilder("jsonJob", jobRepository)
                .start(jsonStep())
                .listener(jobListener)
                .build();
    }

    private Step jsonStep() {
        return new StepBuilder("jsonStep", jobRepository)
                .<Log, Log>chunk(3, transactionManager)
                .reader(jsonItemReader())
                .processor(bizItemProcessor)
                .writer(list -> list.forEach(data -> System.err.println("jsonItemReader : " + data)))
                .build();
    }

    private ItemReader<Log> jsonItemReader() {
        ClassPathResource resource = new ClassPathResource("data/log.json");
        JacksonJsonObjectReader<Log> objectReader = new JacksonJsonObjectReader<>(Log.class);
        JsonItemReader<Log> reader = new JsonItemReader<>(resource, objectReader);
        reader.setName("dataJsonItemReader");
        return reader;
    }

}
